import { message, copy, getCurrentTabId } from './scripts/util.js'
import { parse, parseHtml } from './scripts/contain.js'

// 绑定复制事件
document.getElementById("copy")?.addEventListener('click', () => {
  const iframe = document.getElementById('theFrame') as HTMLIFrameElement;
  let editDom = document.getElementById("edit") as HTMLTextAreaElement
  let content = editDom?.value
  console.log("content", content);
  iframe?.contentWindow?.postMessage({ content }, '*');
})

// 提取商品信息
document.getElementById("extract")?.addEventListener('click', async () => {
  // 1 发送信息获取页面内容
  const tabId = await getCurrentTabId() as number
  const connect = chrome.tabs.connect(tabId, { name: 'getContent' });
  connect.postMessage(null)
  // 2 解析内容
  connect.onMessage.addListener((htmlContent) => {
    parseHtml(htmlContent)
  })
})


// 监听沙盒消息回传
window.addEventListener('message', function ({ data }) {
  try {
    console.log("data", data);
    let psrseContent = parse(data)
    copy(psrseContent as string, () => message.success("复制成功"))
  } catch (error) {
    message.error("插件异常，请上报错误！")
  }
});
